/* cl.ext.fileMultiple 0.1*/
(
    function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory);
        } else if (typeof module === 'object' && module.exports) {
            module.exports = function( root, jQuery ) {
                if ( jQuery === undefined ) {
                    if ( typeof window !== 'undefined' ) {
                        jQuery = require('jquery');
                    }
                    else {
                        jQuery = require('jquery')(root);
                    }
                }
                factory(jQuery);
                return jQuery;
            };
        } else {
            factory(jQuery);
        }
    }(
    function ($){
        var defaults={
            maxMultiple:9,
            checkData:[],//width | height|filetype|maxSize|isImgType|allowExt|allowMime
            checkBeforeCallback:null,
            checkCallback:null,
            successCallback:null
        };
        var defaultsMime={
            "image/jpg":"jpg",
            "image/jpeg":"jpg",
            "image/pjpeg":"jpg",
            "image/png":"png",
            "image/x-png":"png",
            "image/gif":"gif"
        };
        var $modalCommon={
            getDefaults :function () {
                return defaults
            },
            getOptions : function (elementData,options) {
                options=$.ExtCommon.isCheckEmpty(options)?{}:options;
                var optionBase =$.ExtCommon.initMergeJson(elementData,options);
                optionBase =$.ExtCommon.initMergeJson(this.getDefaults(),optionBase);
                return optionBase
            },
            getExtRegex: function(ext) {
                if(!ext) return null;
                if(typeof ext === 'string') ext = [ext];
                if(ext.length === 0) return null;
                return new RegExp("\.(?:"+ext.join('|')+")$", "i");
            },
            getMimeRegex:function(mime) {
                if(!mime) return null;
                if(typeof mime === 'string') mime = [mime];
                if(mime.length === 0) return null;
                return new RegExp("^(?:"+mime.join('|').replace(/\//g, "\\/")+")$", "i");
            }
        };
        var modalOperateElement=function(element,options){
            this.element =element;
            this.optionModal=options;
            this.hasFile = 'File' in window;
        };
        modalOperateElement.prototype = {
            init: function () {
                this.bindEvent();
            },
            bindEvent:function(){
                var self=this;
                self.element.off("change").on("change", function(){
                    var len=this.files.length;
                    if(len>0){
                        var errMsg="";
                        if(len>self.optionModal.maxMultiple){
                            errMsg="最多选择"+self.optionModal.maxMultiple+"个文件";
                        }
                        if(self.optionModal.checkBeforeCallback){var temp=self.optionModal.checkBeforeCallback(errMsg)}
                        if(errMsg.length===0 && self.optionModal.checkCallback){
                            self.checkFileList(this.files,function (result) {
                                var success=[];
                                var fail=[];
                                $.each(result,function (i,info) {info.success?success.push(info):fail.push(info);});
                                self.optionModal.checkCallback({success:success,fail:fail})
                            });
                        }
                    }
                });
            },
            checkFileList:function (files,cb) {
                var self=this;
                var arrResult=[];
                var c=0;
                for(var f = 0; f < files.length; f++) {
                    (function (file,i) {
                        $.when(self.getImgFileWh(file)).done(function(wh){
                            ++c;
                            var result=self.checkFile(file,wh.width,wh.height);
                            arrResult.push(result);
                            if(c===files.length && cb){
                                cb(self.checkFileRepeatWh(arrResult))
                            }
                        })
                    })(files[f],f);
                }
            },
            getImgFileWh: function(file) {
                var deferred = new $.Deferred;
                if(this.hasFile && file instanceof File) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var imgCheck = $("<img />").attr("src", e.target.result).get(0);
                        setTimeout(function(){
                            var w=imgCheck.width;
                            var h=imgCheck.height;
                            deferred.resolve({width:w,height:h});
                        },200);
                    };
                    reader.readAsDataURL(file);
                }
                return deferred.promise();
            },
            checkFile:function (file,w,h) {
                var self=this;
                var isExist=false;
                var filename = !this.hasFile ? file : file.name;
                var type =!this.hasFile ? "" : $.trim(file.type);
                var result={
                    success:false,file:file,fileName:filename,width:w,height:h,err:[],errMsg:[],
                    fileType:defaultsMime[type]||filename.substr(filename.lastIndexOf(".")+1),size:(file.size/1024).toFixed(2)
                };
                for(var i=0;i<self.optionModal.checkData.length;i++){
                    var checkInfo=self.optionModal.checkData[i];
                    if(checkInfo.width==w&&checkInfo.height==h){
                        isExist=true;
                        result.original=checkInfo;
                        var allowExt= $modalCommon.getExtRegex(checkInfo.allowExt);
                        var allowMime= $modalCommon.getMimeRegex(checkInfo.allowMime);
                        var maxSize=checkInfo.maxSize?checkInfo.maxSize*1024 : false;
                        if( allowExt && !allowExt.test(filename) ) {result.err.push("ext")}
                        if(type.length>0 &&allowMime && !allowMime.test(type)){result.err.push("mime")}
                        if( maxSize && file.size > maxSize ) {result.err.push("size")}
                    }
                }
                if(!isExist){result.err.push("exist")}
                if(result.err.length>0){
                    $.each(result.err,function (i,t) {
                        var errmsg="";
                        switch (t){
                            case "exist":
                                errmsg="宽高不在范围内";
                                break;
                            case "ext":
                            case "mime":
                                errmsg="文件类型不正确";
                                break;
                            case "size":
                                errmsg="文件大小不正确";
                                break;
                        }
                        if(errmsg.length>0){result.errMsg.push(errmsg)}
                    });
                }
                result.wh=result.width+"x"+result.height;
                result.success=result.err.length===0;
                return result;
            },
            checkFileRepeatWh:function(list){
                var tempGroup= $.ExtCommon.getJsonByGroup(list,"wh");
                $.each(list,function(i,info){
                    if(tempGroup.hasOwnProperty(info.wh) && tempGroup[info.wh].length>1){
                        info.success=false;
                        info.err=["repeat"];
                        info.errMsg=["宽高("+info.wh+")重复"]
                    }
                });
                return list;
            },
            changeCheckData:function(data){
                this.optionModal.checkData=data;
            },
            destroyHtml:function(){

            }
        };
        var FileMultipleExtModal = function(element, options) {
            var self=this;
            self.element = $(element);
            self.optionBase=$modalCommon.getOptions(self.element.data(),options);
            self.optionBase.initShowType="multipleFile";
            switch(self.optionBase.initShowType){
                case "multipleFile":
                    self.elementOperate=new modalOperateElement(this.element,this.optionBase);
                    self.elementOperate.init();
                    break;
            }
        };
        FileMultipleExtModal.prototype = {
            changeCheckData:function(data){
                this.elementOperate.changeCheckData(data)
            }
        };
        $.fn.ExtFileMultiple = function(options) {
            var dataFun;
            this.each(function() {
                var el = $(this);
                var tempData=el.data('ExtFileMultiple');
                if (tempData) {
                    if (typeof  options === "string") {
                        if (tempData[options]) {
                            dataFun =tempData[options]()
                        } else {
                            dataFun = tempData
                        }
                    } else {
                        dataFun = tempData
                    }
                } else {
                    dataFun = new FileMultipleExtModal(el, options);
                    el.data('ExtFileMultiple', dataFun);
                }
            });
            return dataFun;
        };
        return FileMultipleExtModal;
    })
);
